<?php

namespace App\Http\Middleware;

use Closure;

/**
 * 允许跨域
 * Class checkAppKuaYuMiddleware
 * @package app\http\middleware
 */
class OpenKuaYuMiddleware
{
    /**
     * 中间件处理函数
     * @param $request
     * @param Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $this->allKuaYu($request, env('IS_ALLOW_ORIGIN', false));
        return $next($request);
    }

    /**
     * 设置跨域操作
     * @param $request
     * @param bool $isOpen
     */
    protected function allKuaYu($request, $isOpen = false)
    {
        if ($isOpen) {
            header('Access-Control-Allow-Origin:*'); // *代表允许任何网址请求
            header('Access-Control-Expose-Headers:Content-Disposition,filename'); // *允许前端获取头
            header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE,PUT'); // 允许请求的类型
            header('Access-Control-Allow-Credentials: true'); // 设置是否允许发送 cookies
            header('Access-Control-Allow-Headers: Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin, SC-API-TOKEN');
            if ($request->method() == "OPTIONS") {
                die(200);
            }
        }
    }
}
